package cn.iocoder.yudao.module.spider.shopee;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.validation.BeanValidationResult;
import cn.hutool.extra.validation.ValidationUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.spider.enums.ModuleEnums;
import cn.iocoder.yudao.module.spider.enums.SiteEnums;
import cn.iocoder.yudao.module.spider.enums.SyncEnums;
import cn.iocoder.yudao.module.spider.shopee.request.ShopeeGetAccountRequest;
import cn.iocoder.yudao.module.spider.shopee.request.ShopeeGetMerchantShopListRequest;
import cn.iocoder.yudao.module.spider.shopee.request.ShopeeMpskuGetMpskuListV2Request;
import cn.iocoder.yudao.module.spider.shopee.request.ShopeeSellerRequest;
import cn.iocoder.yudao.module.spider.shopee.response.ShopeeSellerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ShopeeSellerSpider {
    private static String spiderUrl;

    @Value("${spider.url}")
    public void setSpiderUrl(String url) {
        spiderUrl = url;
    }

    /**
     * 获取账户信息
     * @param req 请求对象
     * @return 请求结果
     * @throws RuntimeException 异常
     */
    public static String getAccount(ShopeeGetAccountRequest ...req) throws RuntimeException {
        List<ShopeeSellerRequest> collect = Arrays.stream(req).map(e -> {
            validateRequest(e);
            ShopeeSellerRequest request = new ShopeeSellerRequest();
            BeanUtil.copyProperties(e, request);
            request.setSite(SiteEnums.SHOPEE.getName());
            request.setModule(ModuleEnums.GET_ACCOUNT.getModule());
            request.setSync(SyncEnums.SYNC.getValue());
            return request;
        }).collect(Collectors.toList());
        return postRequest(collect.toArray(new ShopeeSellerRequest[collect.size()]));
    }

    /**
     * 异步获取商家店铺
     * @param req 请求对象
     * @return 请求结果
     * @throws RuntimeException 异常
     */
    public static String getMerchantShopList(ShopeeGetMerchantShopListRequest ...req) throws RuntimeException {
        List<ShopeeSellerRequest> collect = Arrays.stream(req).map(e -> {
            validateRequest(e);
            ShopeeSellerRequest request = new ShopeeSellerRequest();
            BeanUtil.copyProperties(req, request);
            request.setSite(SiteEnums.SHOPEE.getName());
            request.setModule(ModuleEnums.GET_MERCHANT_SHOP_LIST.getModule());
            request.setSync(SyncEnums.ASYNC.getValue());
            return request;
        }).collect(Collectors.toList());
        return postRequest(collect.toArray(new ShopeeSellerRequest[collect.size()]));
    }

    public static String getMpSkuList(ShopeeMpskuGetMpskuListV2Request...req) throws RuntimeException {
        List<ShopeeSellerRequest> collect = Arrays.stream(req).map(e -> {
            validateRequest(e);
            validateRequest(req);
            ShopeeSellerRequest request = new ShopeeSellerRequest();
            BeanUtil.copyProperties(req, request);
            request.setSite(SiteEnums.SHOPEE.getName());
            request.setModule(ModuleEnums.GET_MPSKU_LIST.getModule());
            request.setSync(SyncEnums.ASYNC.getValue());
            return request;
        }).collect(Collectors.toList());
        return postRequest(collect.toArray(new ShopeeSellerRequest[collect.size()]));
    }

    /**
     * 校验入参
     * @param obj 请求对象
     * @throws RuntimeException 异常
     */
    public static void validateRequest(Object obj)  throws RuntimeException {
        if(true) {
            return;
        }
        BeanValidationResult validationResult = ValidationUtil.warpValidate(obj);
        if(!validationResult.isSuccess()) {
            throw new RuntimeException(validationResult.getErrorMessages().toString());
        }
    }

    /**
     * 网络请求
     * @param request 请求对象
     * @return 请求结果
     * @throws RuntimeException 异常
     */
    public static String postRequest(ShopeeSellerRequest ...request) throws RuntimeException {
        String requestBody = JSONUtil.toJsonStr(request);
        log.info("fetcher remote request body: {}", requestBody);
        HttpResponse response = HttpUtil.createPost(spiderUrl)
                .body(JSONUtil.toJsonStr(request))
                .execute();
        log.info("fetcher remote response body: {}", requestBody);
        if (!response.isOk()) {
            log.info("fetcher remote network error: {}", response.body());
            throw new RuntimeException(response.body());
        }
        ShopeeSellerResponse resp =  JSONUtil.toBean(response.body(), ShopeeSellerResponse.class);
        if (resp.getCode() != 200) {
            log.info("fetcher remote response error: {}", resp.getMsg());
            throw  new RuntimeException(resp.getMsg());
        }
        return resp.getData();
    }
}
